<html lang="en">

<head>
    <meta charset="utf-8" />
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>
    <script src="/js/my.js"></script>
    <title>登录</title>
    <style>
        .center {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
    <div class="center">
        <form id="loginForm">
            <table>
                <tr>
                    <td>用户名</td>
                    <td><input id="user" name="user" type="text" size="20" autofocus /></td>
                </tr>
                <tr>
                    <td>密码</td>
                    <td><input id="pass" name="pass" type="password" size="20" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <button type="submit">登录</button>
                        <button type="button" onclick="showRegisterForm()">注册</button>
                    </td>
                </tr>
            </table>
        </form>

        <!-- 注册表单 -->
        <form id="registerForm" style="display: none;">
            <table>
                <tr>
                    <td colspan="2" align="center">
                        <h3>用户注册</h3>
                    </td>
                </tr>
                <tr>
                    <td>用户名</td>
                    <td><input id="regUser" name="user" type="text" size="20" /></td>
                </tr>
                <tr>
                    <td>密码</td>
                    <td><input id="regPass" name="pass" type="password" size="20" /></td>
                </tr>
                <tr>
                    <td>确认密码</td>
                    <td><input id="confirmPass" name="confirmPass" type="password" size="20" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <button type="submit">注册</button>
                        <button type="button" onclick="showLoginForm()">返回登录</button>
                    </td>
                </tr>
            </table>
        </form>

        <span id="msg" style="color: red;"></span>
    </div>
    <script>
        // 显示注册表单
        function showRegisterForm() {
            $('#loginForm').hide();
            $('#registerForm').show();
            $('#msg').html('');
        }

        // 显示登录表单
        function showLoginForm() {
            $('#registerForm').hide();
            $('#loginForm').show();
            $('#msg').html('');
        }

        $(document).ready(function () {
            // 登录表单提交
            $('#loginForm').submit(function (event) {
                event.preventDefault();    //阻止form的默认行为（即form里的内容会拼在url里发起Get请求，这样原始密码就暴露了）
                const form = document.querySelector("#loginForm");
                var formData = new FormData(form);
                var pass = formData.get("pass");   //取得用户输入的原始密码
                var digest = CryptoJS.MD5(pass);
                formData.set("pass", digest);   //直接在客户端对密码执行哈希
                $.ajax({
                    url: "/login/submit",
                    data: formData,
                    method: 'post',
                    processData: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    success: function (result) {
                        window.sessionStorage.setItem("auth_token", result.token);       //往sessionStorage里添加数据，不在不同的浏览器窗口之间共享（即使打开的是同一个url），关闭浏览器后sessionStorage自动清空
                        // 登录成功后重定向到博客列表页
                        window.location.href = "/blog/list/" + result.uid;
                    }
                }).fail(function (result, result1, result2) {
                    $('#msg').html(result.responseJSON.msg);  //正常来说,应该按result.responseJSON.code重新组织话术
                });
            });

            // 注册表单提交
            $('#registerForm').submit(function (event) {
                event.preventDefault();
                const form = document.querySelector("#registerForm");
                var formData = new FormData(form);
                var pass = formData.get("pass");
                var confirmPass = formData.get("confirmPass");
                var user = formData.get("user");

                // 客户端验证
                if (!user || user.trim().length === 0) {
                    $('#msg').html('用户名不能为空');
                    return;
                }
                if (!pass || pass.length < 6) {
                    $('#msg').html('密码长度至少6位');
                    return;
                }
                if (pass !== confirmPass) {
                    $('#msg').html('两次输入的密码不一致');
                    return;
                }

                // 对密码进行MD5加密
                var digest = CryptoJS.MD5(pass);
                formData.set("pass", digest);
                formData.delete("confirmPass"); // 删除确认密码字段

                $.ajax({
                    url: "/register/submit",
                    data: formData,
                    method: 'post',
                    processData: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    success: function (result) {
                        $('#msg').html('<span style="color: green;">注册成功，请登录</span>');
                        setTimeout(showLoginForm, 2000); // 2秒后自动切换到登录表单
                    }
                }).fail(function (result, result1, result2) {
                    $('#msg').html(result.responseJSON.msg);
                });
            });
        }); 
    </script>
</body>